import {
  asyncRoutes,
  constantRoutes
} from '@/router'
import {
  getCurrentUserNav
} from '@/api/login'
import {
  getStore,
  setStore
} from '@/utils/store'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(route) {

}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
// export function filterAsyncRoutes(routes, roles) {
//   const res = []

//   routes.forEach(route => {
//     const tmp = {
//       ...route
//     }
//     window.console.log(tmp)
//     if (hasPermission(roles, tmp)) {
//       if (tmp.children) {
//         tmp.children = filterAsyncRoutes(tmp.children, roles)
//       }
//       res.push(tmp)
//     }
//   })

//   return res
// }
function isURL(s) {
  return /^http[s]?:\/\/.*/.test(s)
}
// 动态路由
export function filterAsyncRoutes(aMenu = [], first) {
  const aRouter = []
  const propsConfig = aMenu
  const propsDefault = {
    label: propsConfig.label || 'label',
    path: propsConfig.path || 'path',
    icon: propsConfig.icon || 'icon',
    children: propsConfig.children || 'children',
    meta: propsConfig.meta || 'meta',
    keepAlive: propsConfig.keepAlive || 'keepAlive'
  }
  if (aMenu.length === 0) return
  for (let i = 0; i < aMenu.length; i++) {
    const oMenu = aMenu[i]
    // if (this.routerList.includes(oMenu[propsDefault.path])) return
    const path = (() => {
      if (!oMenu[propsDefault.path]) {
        return
      } else if (first) {
        return oMenu[propsDefault.path].replace('/index', '')
      } else {
        return oMenu[propsDefault.path]
      }
    })()

    // 特殊处理组件
    const component = 'views' + oMenu.path

    const name = oMenu[propsDefault.label]

    const icon = oMenu[propsDefault.icon]

    const keepAlive = oMenu[propsDefault.keepAlive]

    const children = oMenu[propsDefault.children]

    const meta = {
      icon: icon,
      title: name,
      noCache: keepAlive == '1'
    }
    const isChild = children.length !== 0
    const oRouter = {
      path: path,
      component(resolve) {
        // 判断是否为首路由
        if (first) {
          // window.console.log('w我爱上的那可是21323去问请问请问驱蚊器3')
          require(['../../layout'], resolve)
          // 判断是否为多层路由
        } else if (isChild && !first) {
          // window.console.log('w我爱上的那可是21323去问驱蚊器3')
          require(['../../layout/components/AppMain'], resolve)

          // 判断是否为最终的页面视图
        } else {
          // window.console.log('w我爱上的那可是')
          require([`../../${component}.vue`], resolve)
        }
      },
      name: name,
      icon: icon,
      meta: meta,
      redirect: (() => {
        if (!isChild && first && !isURL(path)) return `${path}/index`
        else return ''
      })(),
      // 处理是否为一级路由
      children: !isChild ? (() => {
        if (first) {
          if (!isURL(path)) oMenu[propsDefault.path] = `${path}/index`
          return [{
            component(resolve) {
              require([`../../${component}.vue`], resolve)
            },
            icon: icon,
            name: name,
            meta: meta,
            path: 'index'
          }]
        }
        return []
      })() : (() => {
        return filterAsyncRoutes(children, false)
      })()
    }
    aRouter.push(oRouter)
    window.console.log(aRouter)
  }
  return aRouter
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = routes.concat(constantRoutes)
  }
}
const actions = {
  generateRoutes({
    commit
  }) {
    return new Promise(resolve => {
      getCurrentUserNav().then(data => {
        const list = data.data
        console.log(list)
        let accessedRoutes
        accessedRoutes = filterAsyncRoutes(list, true)
        window.console.log(accessedRoutes)
        accessedRoutes.push({
          path: '*',
          redirect: '/404',
          hidden: true
        })
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
